package com.hsh.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.hsh.bean.BootStrapSleep;
import com.hsh.bean.Message;
import com.hsh.bean.ResultData;
import com.hsh.bean.Sleep;
import com.hsh.service.SleepService;
import com.hsh.util.DateFormatUtil;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/sleep")
public class SleepRestController {

    @Resource
    private SleepService sleepService;

    /**
     * 用户信息分页显示
     * @param offset
     * @param limit
     * @param sleep
     * @return
     */
    @RequestMapping("/list-data")
    public String list(@RequestParam(defaultValue = "0") int offset,
                             @RequestParam(defaultValue = "5") int limit,
                             Sleep sleep, Model model) {
        System.out.println(sleep);
        //分页查询
        PageInfo<Sleep> sleepPageInfo = sleepService.findSleepByPage(sleep, offset / limit + 1, limit);
        List<BootStrapSleep> bootStrapSleeps = toBootStrap(sleepPageInfo.getList());
        //将查询结果封装到ResultData中显示
        ResultData<BootStrapSleep> resultData = new ResultData<>();
        resultData.setTotal(sleepPageInfo.getTotal());
        resultData.setRows(bootStrapSleeps);
        //将结果封装成JSON格式
        String json = JSON.toJSONString(resultData);
        return json;
    }

    private List<BootStrapSleep> toBootStrap(List<Sleep> sleeps) {
        List<BootStrapSleep> pageData = new ArrayList<>();
        for (Sleep sleep: sleeps){
            Integer sid = sleep.getSid();
            Integer uid = sleep.getUid();
            Float sTime = sleep.getSTime();
            Float sCycle = sleep.getSCycle();
            String sTypeName = sleep.getSTypeName();
            String sDate =
                    sleep.getSDate() == null ? "------" : DateFormatUtil.format(sleep.getSDate());
            BootStrapSleep bootStrapSleep = new BootStrapSleep(sid,uid,sTime,sCycle,sTypeName,sDate);
            pageData.add(bootStrapSleep);
        }
        return pageData;
    }

    @RequestMapping("/delete-data")
    public String delete(Integer sid){
        Integer delete = sleepService.delete(sid);
        Message msg = new Message();
        msg.setState(delete - 1);
        msg.setResult(delete == 1 ?"删除成功":"删除失败");
        return JSON.toJSONString(msg);
    }
}
